import { ipcMain, dialog } from 'electron'
import fs from 'fs'
import {join} from 'path'
import { exec } from 'child_process';


/**
 * 注册音频保存的IPC事件
 */
async function rAudioSaveHandler(data: any) {
  console.log('打印数据', data)
}
function registerAudioSaveHandler() {
  ipcMain.handle('start-record', async (_, data) => {
    return rAudioSaveHandler(data)
  })
}
async function saveRecordingFiles() {
    ipcMain.on('save-file', async (event, blob: ArrayBuffer, filename: string,pathUrl:string) => {
      // const filePath = path.join(app.getPath('downloads'), filename);
      const filePath = join(pathUrl, filename);
      fs.writeFile(filePath, Buffer.from(blob), (err) => {
        if (err) {
          event.reply('save-file-error', err.message)
        }else{
          event.reply('save-file-success', filePath)
        }

      })


  })

}
//切换扬声器
function switchSpeaker() {
  ipcMain.handle('switch-speakers', async (_, deviceId: string) => {
    //判断系统是windows还是mac
    const platform = process.platform;
    console.log("设备信息", deviceId,platform);
    if (platform === 'win32') {
      //windows系统
        await execPromise(`nircmd setdefaultsounddevice "${deviceId}"`);
        return true

    }  else {
      //其他系统
      //提示用户手动切换
      dialog.showMessageBox({
        type: 'info',
        title: '提示',
        message: '请手动切换扬声器'
      })
      return false
    }


  })
}
// 封装 exec 为 Promise
function execPromise(command: string): Promise<void> {
  return new Promise((resolve, reject) => {
    exec(command, (error) => {
      if (error) reject(error);
      else resolve();
    });
  });
}
export default {
  registerAudioSaveHandler,
  saveRecordingFiles,
  switchSpeaker
}
